﻿using Microsoft.Extensions.DependencyInjection;
using System;

namespace TK.Common.BackgroundJob
{
    /// <summary>
    /// 后台任务统一管理扩展
    /// </summary>
    public static class BackgroundJobServiceExtensions
    {
        /// <summary>
        /// 后台任务管理服务
        /// </summary>
        public static IServiceCollection AddTKBackgroundJob(this IServiceCollection services, Action<BackgroundJobOption> optionBuilder = null)
        {
            var option = new BackgroundJobOption { ThreadCount = 2 };
            services.Configure<BackgroundJobOption>((option) =>
            {
                optionBuilder?.Invoke(option);
                option.ThreadCount = option.ThreadCount <= 0 ? 2 : option.ThreadCount;
                option.ThreadCount = option.ThreadCount > 5 ? 5 : option.ThreadCount;
            });
            services.AddSingleton<IBackgroundJobService, BackgroundJobService>();
            services.AddHostedService<JobHostService>();
            return services;
        }
    }
}
